<?php

/**
 * String, number and array functions
 * 
 * @author Dmitry Kopytine <dm9@mylinks.ru>
 * @author Dmitry Leykin <dilesoft@dilesoft.ru>
 */

function dd($var = null)
{
	header("Content-Type: text/html; charset=UTF-8");
	$backtrace = debug_backtrace();
	if (isset($backtrace[2]) and $backtrace[2]["function"] == "ddn")
	{
		echo "<pre>ddn was called on <b>line {$backtrace[2]["line"]}</b> of file <b>{$backtrace[2]["file"]}</b>:\n\n";
	}
	else
	{
		echo "<pre>dd was called on <b>line {$backtrace[0]["line"]}</b> of file <b>{$backtrace[0]["file"]}</b>:\n\n<b>Backtrace:</b>\n";
	}
	
	foreach ($backtrace as $line)
	{
		echo "file <font><b>{$line["file"]}</b></font> on line <font size=\"+1\"><b>{$line["line"]}</b></font>\n";
	}
	
	echo "\n";
	
	foreach (func_get_args() as $idx => $val)
	{
		$num = $idx + 1;
		echo "<b>{$num}</b>:\n";
		//echo htmlspecialchars(var_export($val, true));
		//echo "<br />";
		var_dump($val);
	}
	echo "</pre>";
	die(999);
}

function ddn($pass_count = 1, $var = null)
{
	global $debug_pass_counter;
	$debug_pass_counter++;
	if ($debug_pass_counter >= $pass_count)
	{
		$args = func_get_args();
		call_user_func_array("dd", array_slice($args, 1));
	}
}

function is_positive_number($str)
{
	return preg_match("/^(0|[1-9]([0-9]+)?)$/", $str);
}

function is_good_num($param)
{
	if (is_int($param) && $param >= 0 && $param <= 2147483646)
	{
		return true;
	}
	$ret = is_positive_number($param);
	if ($ret)
	{
		$param = (int)$param;
		$ret = ($param >= 0) && ($param <= 2147483646);
	}
	return $ret;
}

function is_good_num_with_negative($param)
{
	if (is_int($param))
	{
		return true;
	}
	$ret = is_positive_number($param);
	if ($ret)
	{
		$param = (int)$param;
		$ret = $param >= 0 && $param <= 2147483646;
	}
	elseif (substr($param, 0, 1) == "-" and is_positive_number($param = substr($param, 1)))
	{
		$param = (int)$param;
		$ret = $param >= 0 && $param <= 2147483646;
	}
	return $ret;
}

function is_good_id($param)
{
	return is_good_num($param) and (int)$param > 0;
}

function is_good_email($param)
{
	return preg_match("#^[\-_a-z0-9.]+@[\-_a-z0-9.]+$#i", $param);
}

function stripslashes_deep($value)
{
	$value = is_array($value) ? array_map("stripslashes_deep", $value) : stripslashes($value);
	return $value;
}

// функция, обратная к htmlspecialchars
function unhtmlspecialchars($arg)
{
	if (is_string($arg))
	{
		return preg_replace_callback("/&(amp|lt|gt|quot|apos|#(\d+)|#[xX]([a-fA-F\d]+));/", __FUNCTION__, $arg);
	}
	
	$entities = array(
		
		"amp" => "&", 
		"lt" => "<", 
		"gt" => ">", 
		"quot" => "\"", 
		"apos" => "'" 
	);
	if (isset($entities[$arg[1]]))
	{
		return $entities[$arg[1]];
	}
	// обрабатываем только символы с кодами меньше 256
	if ($arg[2])
	{
		$code = (int)$arg[2] & 0xFF;
	}
	if ($arg[3])
	{
		$code = hexdec($arg[3]) & 0xFF;
	}
	if ($code)
	{
		return chr($code);
	}
	return "?";
}

function is_windows()
{
	return strtoupper(substr(PHP_OS, 0, 3)) == "WIN";
}

function univers_filename($file_name, $windows_check = false)
{
	$file_name = str_replace("\\\\", "/", $file_name);
	$file_name = str_replace("\\", "/", $file_name);
	if ($windows_check and is_windows())
	{
		$file_name = str_replace("/", "\\", $file_name);
	}
	return $file_name;
}

function trailing_slash_add($file_name)
{
	if (substr($file_name, -1, 1) != "/")
		$file_name .= "/";
	return $file_name;
}

function trailing_slash_remove($file_name)
{
	if (substr($file_name, -1, 1) == "/")
		$file_name = substr($file_name, 0, -1);
	return $file_name;
}

/**
 * @todo dilesoft full_rmdir -> rmdir_full
 *
 * @param unknown_type $dir
 * @return unknown
 */
function full_rmdir($dir)
{
	if (!is_dir($dir))
	{
		return false;
	}
	
	$files = scandir($dir);
	foreach ($files as $file)
	{
		if ($file == "." || $file == "..")
		{
			continue;
		}
		
		if (!full_rmdir($dir . "/" . $file))
		{
			unlink($dir . "/" . $file);
		}
	}
	
	rmdir($dir);
	return true;
}

function dir_map($dir, $callback, $deep = true)
{
	if (!is_dir($dir))
	{
		return false;
	}
	$files = scandir($dir);
	foreach ($files as $file)
	{
		if ($file == "." || $file == "..")
		{
			continue;
		}
		
		$file = $dir . "/" . $file;
		if (is_dir($file) && $deep)
		{
			dir_map($file, $callback, $deep);
		}
		else
		{
			call_user_func($callback, $file);
		}
	}
	
	return true;
}

function dir_list($dir, $deep = false)
{
	$res = array();
	
	if (!is_dir($dir))
	{
		return false;
	}
	$files = scandir($dir);
	foreach ($files as $file)
	{
		if ($file == "." || $file == "..")
		{
			continue;
		}
		
		$path = $dir . "/" . $file;
		if (is_dir($path) && $deep)
		{
			$res[$file] = dir_list($path, $deep);
		}
		else
		{
			$res[] = $file;
		}
	}
	return $res;
}

function format_file_size($size)
{
	if (($tsize = $size / 1024) < 1)
	{
		return floor($size) . " Bytes";
	}
	else
	{
		$size = $tsize;
		if (($tsize = $size / 1024) < 1)
		{
			return number_format($size, 2, '.', '') . " KB";
		}
		else
		{
			$size = $tsize;
			if (($tsize = $size / 1024) < 1)
			{
				return number_format($size, 2, '.', '') . " MB";
			}
			else
			{
				$size = $tsize;
				return number_format($size, 2, '.', ' ') . " GB";
			}
		}
	}
}

function set_cookie_extended($name, $value = "1", $expires = 0, $path = "", $domain = "", $secure = false, $httponly = false)
{
	header($h = "Set-Cookie: " . rawurlencode($name) . "=" . rawurlencode($value) . (!($expires) ? "" : "; Expires=" . date("r", $expires)) . (empty($path) ? "" : "; path=" . $path) . (empty($domain) ? "" : "; domain=" . $domain) . (!$secure ? "" : "; secure") . (!$httponly ? "" : "; HttpOnly"));
}

function array_merge_good(&$first, $second)
{
	$arrays = func_num_args();
	
	foreach ($second as $key => $value)
	{
		$first[$key] = $value;
	}
}

function nl2br2($string)
{
	$string = str_replace(array(
		
		"\r\n", 
		"\r", 
		"\n" 
	), "<br />", $string);
	return $string;
}

function br2nl($text)
{
	/**
	 * @todo dvs ??? \r\n or \n or \r ???
	 */
	
	/*    return  preg_replace('/<br\\\\s*?\\/??>/i', "\\n", $text);*/
	return preg_replace('/<br\\s*?\/??>/i', "", $text);
}

function send_mail($to, $subject, $message, $additional_headers = null, $additional_parameters = null)
{
	if ($additional_parameters)
	{
		return mail($to, $subject, $message, $additional_headers, $additional_parameters);
	}
	else
	{
		return mail($to, $subject, $message, $additional_headers);
	}
}

if (!function_exists('sys_get_temp_dir'))
{

	// Based on http://www.phpit.net/
	// article/creating-zip-tar-archives-dynamically-php/2/
	function sys_get_temp_dir()
	{
		// Try to get from environment variable
		if (!empty($_ENV['TMP']))
		{
			return realpath($_ENV['TMP']);
		}
		else if (!empty($_ENV['TMPDIR']))
		{
			return realpath($_ENV['TMPDIR']);
		}
		else if (!empty($_ENV['TEMP']))
		{
			return realpath($_ENV['TEMP']);
		}
		
		// Detect by creating a temporary file
		else
		{
			// Try to use system's temporary directory
			// as random name shouldn't exist
			$temp_file = tempnam(md5(uniqid(rand(), TRUE)), '');
			if ($temp_file)
			{
				$temp_dir = realpath(dirname($temp_file));
				unlink($temp_file);
				return $temp_dir;
			}
			else
			{
				return FALSE;
			}
		}
	}
}

function get_microtime()
{
	list($usec, $sec) = explode(" ", microtime());
	return ((float)$usec + (float)$sec);
}

/**
 * @todo
 */
function file_put_contents_safe($file_path, $content = "")
{
	if (!file_exists($dir = dirname($file_path)))
	{
		mkdir($dir, 0777, true);
	}
	return file_put_contents($file_path, $content);
}

function file_get_contents_safe($file_path)
{
	return file_get_contents($file_path);
}

function unlink_safe($file_path)
{
	if (file_exists($file_path))
	{
		return unlink($file_path);
	}
}

function rename_safe($old_file_path, $new_file_path)
{
	if (file_exists($new_file_path))
	{
		unlink($new_file_path);
	}
	return rename($old_file_path, $new_file_path);
}

function get_file_contents_remove_rn($tpl_name)
{
	if (file_exists($tpl_name))
	{
		return str_replace(array(
			
			"'", 
			"\r\n", 
			"\n" 
		), array(
			
			"\'", 
			"", 
			"" 
		), file_get_contents($tpl_name));
	}
	else
	{
		return "Template {$tpl_name} was not found";
	}
}

?>